package com.anabur.system;  
  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;

import org.primefaces.event.FileUploadEvent;

public class FileUploadController implements Serializable{  
  
	private static final long serialVersionUID = 1L;
	
	public static File handleFileUpload(FileUploadEvent event) {
		String newFileDirectory = System.getProperty("java.io.tmpdir") + event.getFile().getFileName();
		File file = null;
		try {
			file = new File(newFileDirectory);
			InputStreamReader  in = new InputStreamReader(event.getFile().getInputstream());
			//InputStreamReader  in = new InputStreamReader(event.getFile().getInputstream(), Charset.forName("UTF-8"));
			BufferedReader br = new BufferedReader(in);
			PrintWriter pw = new PrintWriter(new FileWriter(newFileDirectory));
			String line = null;
			while ((line = br.readLine()) != null) {
				line = line.replaceAll(">\\s*<", "><");
				line = line.replaceAll("\uFFFD", " ");
			    pw.println(line.trim());
			    pw.flush();
			}
			pw.close();
			br.close();
			in.close();
			
//			FileOutputStream fos = new FileOutputStream(file);
//			InputStream is = event.getFile().getInputstream();
//			byte[] buffer = new byte[is.available()];
//			int reading;
//			while (true) {
//				reading = is.read(buffer);
//				if (reading < 0)
//					break;
//				fos.write(buffer, 0, reading);
//				fos.flush();
//			}
//			fos.close();
//			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
}   